$(document).ready(
	function(){
		$("#connErrorInfo")[0].style.display = "none";
		
		$.As = [];
		datas = null;
		
		//初始化站点select，只加入与用户相绑定的site
		var siteSelect = $("#gridContent").find("#sites");
		siteSelect.empty();		
		$.ajax({
			type: "POST",
			url : getContextPath()+"/user/getUserSites.do",
			data : {},
			dataType : "json",
			async : false,
			cache: false,
			error : function(textStatus, errorThrown) {
				alert("系统ajax交互错误: " + textStatus);
			},
			success : function(data, textStatus) {
				if (data != null) {
					siteList = data;
					for (var i=0; i<data.length; i++) {
						//ie8不支持
						//siteSelect.append(new Option(data[i].id+":"+data[i].name, data[i].id));
						siteSelect.append('<option value="'+data[i].id+'">'+data[i].id+":"+data[i].name+'</option>');
					}
				}
			}
		});
		//设置siteSelect的change事件
		siteSelect.change(function() {
			$("#curSite").val(siteSelect.val());
			activateRealTimeData();
		});
		//根据传进来的siteID，$("#sites").val()选中select中的记录，然后触发
		siteSelect.val($("#curSite").val()).change();
	}
);

function activateRealTimeData() {
		//table
		//var infoTable = $("itemBlocks");
		//获取与该site相关的item，建立table
		//var siteID = $("#curSite").val();
		var siteID = $("#gridContent").find("#sites").val();
		//清空$("#itemForm")的内容
		$("#itemForm").html("");
		$.ajax({
			type: "POST",
			url : getContextPath()+"/site/item/getItemObjBySite.do",
			data : {siteID : siteID},
			dataType : "json",
			async : false,
			cache: false,
			error : function(textStatus, errorThrown) {
				//alert("系统ajax交互错误: " + textStatus);
			},
			success : function(data, textStatus) {
				if (data != null) {
					datas = data;
					//往itemBlocks插入，每一行插入3个
					var trNum = 0;
					var table = $("<table></table>");
            	    table.attr("id","userSitesTb").attr("class","customPromptTbPadding");
					var tr = $("<tr></tr>");
            	    var td = $("<td></td>");
            	    td.attr("class", "tddiv");
            	    var divv = $("<div></div>");
            	    //divv.attr("class", "cornerdiv");
            	    var objTr = null;
            	    var objTd = null;
            	    var objDiv = null, objMeter=null;
					for (var i=0; i<data.length; i++) {
						if (trNum ==0) {
							objTr = tr.clone();
						}
						objTd = td.clone();
						objDiv = divv.clone();
//						objDiv.data({siteID : siteID, itemID : data[i].item.id});
						$.As[i] = $("<a onclick='showDialog("+i+");' href='javascript:void(0)'><img alt=\"显示图表\" src=\""+getContextPath() +"/resources/images/icons/showChart.gif\"//></a>");
						objDiv.append("监测项目："+data[i].item.name);
						objDiv.append($.As[i]);
						objDiv.append("<br/>");
						objDiv.append("超标上限值："+data[i].overMaxValue+"<br/>");
						objDiv.append("超标下限值："+data[i].overMinValue+"<br/>");
						
						//objDiv.append($.As[i]);
						//下面是odometer
						objMeter = $("<div></div>").clone();
						objMeter.attr("class", "metertick").attr("id", "meter_"+data[i].id);
						objMeter.jOdometer({
							id: data[i].id,
					        counterStart:'000.00',  //Number we are starting with. To get a specific number of digits/decimals it have to be a string (e.g. '0005.50')
							counterEnd:false,  //The counter stop when reach this number. If it is the same as counterStart the odometer is static. False to don't stop never
					        delayTime: $("refreshTime").val(),//20000, //Delay between each number change//20秒更新一次
					        increment: 1,  //Number increment after each delayTime
							speed:500,  //Speed for the change number animation
					        easing: "easeOutElastic",  //Easing for the change number animation. Other than 'swing' or 'linear' must be provided by plugin		
					        numbersImage: getContextPath()+'/resources/images/odometer-image/numbers.png',  //Image used for the numbers
							offsetRight: 0,  //Distance to the right
					        spaceNumbers: 0,  //Separation between the numbers' columns
					        widthDot: 8,  //Decimal dot's special width
							formatNumber: false, //Whether to format the number with commas every 3 digits
							url: getContextPath()+"/site/site/detailvalue.do",//调用ajax的url
							data: {siteID : siteID, itemID : data[i].item.id}
						});
						objDiv.append(objMeter);
						//加入单位
						objUnit = $("<span color='red' class='valueUnitShow'></span>").clone();
						objUnit.append(data[i].standUnit);
						objDiv.append(objUnit);
						//
						objTd.append(objDiv);
						objTr.append(objTd);
						trNum = trNum + 1;
						if (trNum==3) {
							table.append(objTr);
							trNum=0;
						}		
					}
					if (trNum!=0) {
						table.append(objTr);
					}
					$("#itemForm").append(table);
				}
			}
		});
		/**
		//设置div的圆角矩形
		settings = {
				tl: { radius: 20 },
		        tr: { radius: 20 },
		        bl: { radius: 20 },
		        br: { radius: 20 },
		        antiAlias: true,
		        autoPad: true,
		        validTags: ["div"]
		};
		$('.cornerdiv').corner(settings);
		//setInterval(showContent, 3000);
		**/
}

// getContextPath
function getContextPath() {
	var pathName = document.location.pathname;
    var index = pathName.substr(1).indexOf("/");
    var result = pathName.substr(0,index+1);
    return result;
};

function showContent() {
	$("#gridContent").append('KKK<br/>');
}

function showDialog(index) {
	var siteID = $("#curSite").val(),
		itemID = datas[index].item.id;
	 var data = [],
     time = (new Date()).getTime();

	 $.ajax({
	 	url: getContextPath()+"/site/site/last24HItemsBySite.do",
	 	data: {siteID: siteID, itemID: itemID},
	 	dataType: 'json',
	 	success: function(seconds) {
//	 		if (seconds) {
//	 			for (var i = 23; i >= 0; i--) {
//	 				data.push({
//	                     x: time - i * 4000,
//	                     y: parseFloat(new Number(seconds[i].value).toFixed(2))
//	  				 });
//	 			}
//	 		} else {
//	 			 for (var i = -23; i <= 0; i++) {
//	 				 data.push({
//	                    x: time + i * 4000,
//	                    y: 0
//	 				 });
//	 			 }
//	 		}
	 		if (!seconds) {
	 			alert("没有数据");
	 			return;
	 		}
	 		var x_cats = [], series = [{data:[]}];
	 		for (var i = seconds.length-1; i >= 0; i--) {
	 			x_cats.push(seconds[i].time);
	 			series[0].name = datas[index].item.name;
	 			series[0].data.push(
	 				parseFloat(new Number(seconds[i][itemID].value).toFixed(2))
  				);
 			}
	 		
	 		//显示图表
	 		$("#container").empty().dialog({
	 			width: 960,
	 			height: 470
	 		}).genLineChart({
//	 			title: "实时数据 - " + datas[index].item.name,
//	 			ytitle: datas[index].item.name,
//	 			url: getContextPath()+"/site/site/detailvalue.do",
//	 			data: {siteID : siteID, itemID : itemID},
//	 			series: data
	 			title: datas[index].item.name + ' 24小时数据',
//				subtitle: $.format('<b>站点：{0}</b>时间：{1} ~ {2}',siteText, $('#startDate').val(), $('#endDate').val()),
				ytitle: '监测值',
				x_cats: x_cats,
				series: series
	 		}).chartControll({
	 			left: function() {
	 				if (index == 0) $.As[datas.length-1].click();
	 				else $.As[index-1].click();
	 			},
	 			right: function() {
	 				if (index == datas.length-1) $.As[0].click();
	 				else $.As[index+1].click();
	 			}
	 		});
	 	}
	 });
}

